<script setup>
import { onMounted, ref } from "vue";
import {
  queryStudentPageApi,
  queryStudentByIdApi,
  addStudentApi,
  deleteStudentApi,
  updateStudentsApi,
  violationStudentsApi,
} from "@/api/student";
import { ElMessage, ElMessageBox } from "element-plus";
import { queryAllClazzApi } from "@/api/clazz";

// 定义 查询表单
const searchClazz = ref({
  name: "",
  degree: "",
  clazzId: "",
});

// 定义 学员列表
let studentList = ref([]);
// 定义 学生类
const student = ref({
  id: "",
  name: "",
  no: "",
  gender: "",
  phone: "",
  degree: "",
  idCard: "",
  isCollege: "",
  address: "",
  graduationDate: "",
  violationCount: "",
  violationScore: "",
  clazzId: "",
  createTime: "",
  updateTime: "",
});
// 定义 分页
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 处理分页大小变化
const handleSizeChange = (newSize) => {
  pageSize.value = newSize;
  handleSearch();
};
// 处理页数变化
const handleCurrentChange = (newPage) => {
  currentPage.value = newPage;
  handleSearch();
};

// 学员列表查询
const handleSearch = async () => {
  const result = await queryStudentPageApi(
    searchClazz.value.name,
    searchClazz.value.degree,
    searchClazz.value.clazzId,
    currentPage.value,
    pageSize.value
  );
  if (result.code === 1) {
    studentList.value = result.data.rows;
    total.value = result.data.total;
  }
};

// 生命周期钩子
onMounted(async () => {
  handleSearch();
  // 加载所有班级数据
  const result = await queryAllClazzApi();
  if (result.code) {
    clazzList.value = result.data.rows;
  }
});

// 清空查询
const handleClear = () => {
  searchClazz.value = {
    name: "",
    degree: "",
    clazzId: "",
  };
  handleSearch();
};

// 定义性别列表数据
const genders = ref([
  { name: "男", value: 1 },
  { name: "女", value: 2 },
]);

// 定义学历列表数据
const degrees = ref([
  { name: "初中", value: 1 },
  { name: "高中", value: 2 },
  { name: "大专", value: 3 },
  { name: "本科", value: 4 },
  { name: "硕士", value: 5 },
  { name: "博士", value: 6 },
]);

// 定义班级列表数据
const clazzList = ref([]);

// 添加学员
const handleAdd = () => {
  dialogTitle.value = "添加学员";
  dialogFormVisible.value = true;
};

// 定义 对话框状态
const dialogFormVisible = ref(false);
const dialogViolationFormVisible = ref(false);
// 定义 对话框标题
const dialogTitle = ref("");

// 存储选中的 ID
let selectIds = ref([]);

// 处理复选框选择变化的函数
function handleSelectionChange(selection) {
  selectIds.value = selection.map((item) => item.id);
}

// 保存新学员
const handleSave = async () => {
  let result;
  if (student.value.id) {
    result = await updateStudentsApi(student.value);
  } else {
    result = await addStudentApi(student.value);
  }
  if (result.code === 1) {
    ElMessage.success("保存成功");
    dialogFormVisible.value = false;
    handleSearch();
  } else {
    ElMessage.error(result.msg);
  }
  // 清除对话框表单内容
  student.value = {
    id: "",
    name: "",
    no: "",
    gender: "",
    phone: "",
    degree: "",
    idCard: "",
    isCollege: "",
    address: "",
    graduationDate: "",
    violationCount: "",
    violationScore: "",
    clazzId: "",
    createTime: "",
    updateTime: "",
  };
  if (studentFromRef.value) {
    studentFromRef.value.resetFields();
  }
};

// 取消保存
const cancel = () => {
  dialogFormVisible.value = false;
  // 清除对话框表单内容
  student.value = {
    id: "",
    name: "",
    no: "",
    gender: "",
    phone: "",
    degree: "",
    idCard: "",
    isCollege: "",
    address: "",
    graduationDate: "",
    violationCount: "",
    violationScore: "",
    clazzId: "",
    createTime: "",
    updateTime: "",
  };
  if (studentFromRef.value) {
    studentFromRef.value.resetFields();
  }
};

// 批量删除
const deleteByIds = async () => {
  //弹出一个确认框, 如果确认, 就删除;
  ElMessageBox.confirm("确定删除选中员工吗?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    // 删除员工
    const result = await deleteStudentApi(selectIds.value);
    if (result.code) {
      ElMessage.success("删除员工成功");
      handleSearch();
    } else {
      ElMessage.error(result.msg);
    }
  });
};

// 编辑学员信息
const handleEdit = async (id) => {
  // 数据回显
  const result = await queryStudentByIdApi(id);
  student.value = result.data;
  // 显示对话框
  dialogTitle.value = "修改学员信息";
  dialogFormVisible.value = true;
};

// 违纪处理
const handleViolation = async (id) => {
  dialogViolationFormVisible.value = true;
  student.value.id = id;
};
const saveViolation = async () => {
  const result = await violationStudentsApi(
    student.value.id,
    student.value.violationScore
  );
  if (result.code === 1) {
    ElMessage.success("保存成功");
    dialogViolationFormVisible.value = false;
    handleSearch();
  } else {
    ElMessage.error(result.msg);
  }
  student.value.violationScore = null;
};

// 取消
const cancelViolation = () => {
  dialogViolationFormVisible.value = false;
  student.value.violationScore = null;
};

// 删除学员
const handleDelete = (id) => {
  // 确认弹窗
  ElMessageBox.confirm("请确认是否删除", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      const result = await deleteStudentApi(id);
      if (result.code === 1) {
        ElMessage.success("删除成功");
        handleSearch();
      } else {
        ElMessage.error(result.msg);
      }
    })
    .catch(() => {
      ElMessage.info("取消删除");
    });
};

// 表单校验规则
const studentFromRef = ref();
const rules = ref({
  name: [
    { required: true, message: "请输入学员姓名", trigger: "blur" },
    {
      min: 2,
      max: 10,
      message: "学员姓名的长度应在2到10个字符之间",
      trigger: "blur",
    },
  ],
  no: [{ required: true, message: "请输入学号", trigger: "blur" }, {}],
  gender: [{ required: true, message: "请选择性别", trigger: "blur" }],
  phone: [{ required: true, message: "请输入手机号", trigger: "blur" }],
  idCard: [{ required: true, message: "请输入身份证号码", trigger: "blur" }],
  isCollege: [{ required: true, message: "请选择是否是在校生", trigger: "blur" },],
});
</script>

<template>
<!--  {{ searchClazz }}-->
  <h1>学员管理</h1>
  <br />
  <!-- 表单 -->
  <!-- 学员姓名 -->
  <el-form :inline="true" :model="searchClazz" class="demo-form-inline">
    <el-form-item label="学员姓名">
      <el-input
        v-model="searchClazz.name"
        placeholder="请输入学员姓名"
        clearable
      />
    </el-form-item>
    <el-form-item label="学历">
      <el-select v-model="searchClazz.degree" placeholder="选择最高学历">
        <el-option
          v-for="degree in degrees"
          :key="degree.value"
          :label="degree.name"
          :value="degree.value"
        ></el-option>
      </el-select>
    </el-form-item>
    <!-- 所属班级 -->
    <el-form-item label="所属班级">
      <el-select v-model="searchClazz.clazzId" placeholder="所属班级">
        <el-option
          v-for="clazz in clazzList"
          :key="clazz.id"
          :label="clazz.name"
          :value="clazz.id"
        />
      </el-select>
    </el-form-item>
    <!-- 查询、清空 按钮 -->
    <el-form-item>
      <el-button type="primary" @click="handleSearch">查询</el-button>
      <el-button @click="handleClear">清空</el-button>
    </el-form-item>
  </el-form>
  <!-- 添加班级 按钮 -->
  <el-button type="primary" plain @click="handleAdd"> + 添加学员</el-button>
  <el-button type="danger" plain @click="deleteByIds"> - 批量删除</el-button>
  <br /><br />
  <!-- 展示内容的表格 -->
  <el-table
    :data="studentList"
    border
    style="width: 100%"
    v-on:selection-change="handleSelectionChange"
  >
    <!-- 第一列：复选框 -->
    <el-table-column
      type="selection"
      width="55"
      align="center"
    ></el-table-column>
    <!-- 第二列：姓名 -->
    <el-table-column
      label="姓名"
      prop="name"
      width="100"
      align="center"
    ></el-table-column>
    <!-- 第三列：学号 -->
    <el-table-column
      label="学号"
      prop="no"
      width="120"
      align="center"
    ></el-table-column>
    <!-- 第四列：班级 -->
    <el-table-column
      label="班级"
      prop="clazzId"
      width="100"
      align="center"
    ></el-table-column>
    <!-- 第五列：性别 -->
    <el-table-column
      label="性别"
      prop="gender"
      width="100"
      align="center"
    ></el-table-column>
    <!-- 第六列：手机号 -->
    <el-table-column
      label="手机号"
      prop="phone"
      width="150"
      align="center"
    ></el-table-column>
    <!-- 第七列：最高学历 -->
    <el-table-column
      label="最高学历"
      prop="degree"
      width="150"
      align="center"
    ></el-table-column>
    <!-- 第八列：违纪次数 -->
    <el-table-column
      label="违纪次数"
      prop="violationCount"
      width="100"
      align="center"
    ></el-table-column>
    <!-- 第九列：违纪扣分 -->
    <el-table-column
      label="违纪扣分"
      prop="violationScore"
      width="100"
      align="center"
    ></el-table-column>
    <!-- 第十列：最后操作时间 -->
    <el-table-column
      label="最后操作时间"
      prop="updateTime"
      width="200"
      align="center"
    ></el-table-column>
    <!-- 第十一列：操作 -->
    <el-table-column label="操作" prop="" width="" align="center">
      <template #default="scope">
        <el-button type="primary" v-on:click="handleEdit(scope.row.id)"
          >编辑
        </el-button>
        <el-button type="warning" v-on:click="handleViolation(scope.row.id)"
          >违纪
        </el-button>
        <el-button type="info" v-on:click="handleDelete(scope.row.id)"
          >删除
        </el-button>
      </template>
    </el-table-column>
  </el-table>
  <br />
  <!-- 分页 -->
  <el-pagination
    v-model:current-page="currentPage"
    v-model:page-size="pageSize"
    :page-sizes="[10, 20, 30, 40]"
    layout="sizes, total, prev, pager, next, jumper"
    :total="total"
    @size-change="handleSizeChange"
    @current-change="handleCurrentChange"
  />
  <!-- 对话框 -->
  <el-dialog
    v-model="dialogFormVisible"
    :title="dialogTitle"
    :before-close="cancel"
    width=""
  >
    <el-form
      ref="studentFromRef"
      :rules="rules"
      :model="student"
      label-width=""
    >
      <!-- 第一行 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="姓名" prop="name">
            <el-input
              v-model="student.name"
              placeholder="请输入学员姓名"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="学号" prop="no">
            <el-input v-model="student.no" placeholder="请输入学号"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <!-- 第二行 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="性别" prop="gender">
            <el-select
              v-model="student.gender"
              placeholder="请选择性别"
              style="width: 100%"
            >
              <el-option
                v-for="gender in genders"
                :key="gender.name"
                :label="gender.name"
                :value="gender.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="手机号" prop="phone">
            <el-input
              v-model="student.phone"
              placeholder="请输入手机号"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <!-- 第三行 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="身份证号" prop="idCard">
            <el-input
              v-model="student.idCard"
              placeholder="请输入身份证号码"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="是否院校学员" prop="isCollege">
            <el-select
              v-model="student.isCollege"
              placeholder="请选择"
              style="width: 100%"
            >
              <el-option label="是" value="1"></el-option>
              <el-option label="否" value="0"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <!-- 第四行 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="联系地址">
            <el-input
              v-model="student.address"
              placeholder="请输入联系地址"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="最高学历">
            <el-select
              v-model="student.degree"
              placeholder="请选择"
              style="width: 100%"
            >
              <el-option
                v-for="degree in degrees"
                :key="degree.value"
                :label="degree.name"
                :value="degree.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <!-- 第五行 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="毕业时间">
            <el-date-picker
              v-model="student.graduationDate"
              type="Date"
              style="width: 100%"
              placeholder="选择毕业时间"
              format="YYYY-MM-DD"
            ></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="所属班级">
            <el-select
              v-model="student.clazzId"
              placeholder="请选择"
              style="width: 100%"
            >
              <el-option
                v-for="clazz in clazzList"
                :key="clazz.id"
                :label="clazz.name"
                :value="clazz.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <!-- 底部按钮 -->
    <template #footer>
      <span
        class="dialog-footer"
        style="display: flex; justify-content: center; gap: 20px"
      >
        <el-button type="primary" @click="handleSave">保存</el-button>
        <el-button @click="cancel">取消</el-button>
      </span>
    </template>
  </el-dialog>
  <!-- 违纪对话框 -->
  <el-dialog
    v-model="dialogViolationFormVisible"
    title="学员违纪处理"
    width="500"
    :before-close="cancelViolation"
  >
    <el-form :model="student">
      <el-form-item label="违纪扣分">
        <el-input v-model="student.violationScore" />
      </el-form-item>
    </el-form>
    <!-- 底部按钮 -->
    <template #footer>
      <span
        class="dialog-footer"
        style="display: flex; justify-content: center; gap: 20px"
      >
        <el-button type="primary" @click="saveViolation">确定</el-button>
        <el-button @click="cancelViolation">取消</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style scoped></style>
